<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>TonPay</h2>
        <p>欢迎登录</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="pwd">
          <el-input
            v-model="loginForm.pwd"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="imageCaptcha">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input
              v-model="loginForm.imageCaptcha"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="Lock"
              style="flex: 1"
            />
            <img
              :src="captchaimg"
              alt="验证码"
              style="
                height: 40px;
                cursor: pointer;
                border: 1px solid #ddd;
                border-radius: 4px;
              "
              @click="getCaptcha"
              title="点击刷新验证码"
            />
          </div>
        </el-form-item>

        <el-form-item prop="secretCode">
          <el-input
            v-model="loginForm.secretCode"
            placeholder="请输入谷歌验证码"
            size="large"
            prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            class="login-btn"
            @click="handleLogin"
          >
            {{ loading ? "登录中..." : "登录" }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { useUserStore } from "@/stores/user";
import { getImageCaptcha } from "@/api/user";

const router = useRouter();
const userStore = useUserStore();

const loginFormRef = ref<FormInstance>();
const loading = ref(false);

const captchaimg = ref("");

const loginForm = reactive({
  phone: "15279293829",
  pwd: "admin",
  imageCaptcha: "",
  imageCaptchaId: "11",
  secretCode: "",
});

const loginRules: FormRules = {
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  imageCaptcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  secretCode: [
    { required: true, message: "请输入谷歌验证码", trigger: "blur" },
  ],
};

// 获取验证码
const getCaptcha = async () => {
  try {
    const res = await getImageCaptcha();
    console.log("验证码响应:", res);
    captchaimg.value = res.data.captcha;
    loginForm.imageCaptchaId = res.data.id;
  } catch (error) {
    console.error("获取验证码失败:", error);
    ElMessage.error("获取验证码失败");
  }
};

// 页面加载时获取验证码
getCaptcha();

const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();
    loading.value = true;

    // 使用用户store的登录方法
    const result = await userStore.login(loginForm);
    console.log('登录结果:', result);
    
    if (result.success) {
      ElMessage.success(result.message);
      
      // 等待用户信息加载完成
      await userStore.fetchUserInfo();
      
      // 使用路由跳转而不是强制刷新
      router.push('/dashboard');
      
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error("登录失败:", error);
    ElMessage.error("登录失败，请重试");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
}

.login-tips {
  text-align: center;
  font-size: 12px;
  color: #999;
  line-height: 1.5;
}

.login-tips p {
  margin: 2px 0;
}
</style>
